import React, { useMemo } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, ReferenceLine } from 'recharts';
import * as PensionCalc from '../utils/pensionCalculations.js';
import { formatCurrency, formatPercentage, formatYears, createTooltipFormatter } from '../utils/chartUtils.jsx';

/**
 * 当地平均工资与收支平衡点关系图
 * @param {Object} props - 组件属性
 * @param {number} props.currentSalary - 当前税前工资
 * @param {number} props.contributionYears - 缴费年限
 * @param {number} props.localAverageSalary - 当前当地上年度在岗职工月平均工资，用作参考点
 * @param {number} props.retirementAge - 退休年龄
 * @param {string} props.employmentType - 就业类型（在职/灵活）
 * @param {number} props.baseRate - 灵活就业基准比例
 * @returns {JSX.Element}
 */
const BreakEvenPointByLocalSalaryChart = ({ 
  currentSalary, 
  contributionYears, 
  localAverageSalary, 
  retirementAge, 
  employmentType,
  baseRate
}) => {
  const data = useMemo(() => {
    const chartData = [];
    const payoutMonths = PensionCalc.getPayoutMonths(retirementAge);
    
    // 设置当地平均工资的变动范围（从当前平均工资的50%到200%）
    const minAvgSalary = Math.floor(localAverageSalary * 0.5);
    const maxAvgSalary = Math.ceil(localAverageSalary * 2);
    const step = Math.round((maxAvgSalary - minAvgSalary) / 20); // 分20个点
    
    for (let avgSalary = minAvgSalary; avgSalary <= maxAvgSalary; avgSalary += step) {
      let personalIndexedSalary, personalAccountTotal, totalContribution;
      
      // 针对不同就业类型计算
      if (employmentType === 'employee') {
        // 在职人员
        const contributionIndex = PensionCalc.calculateContributionIndex(currentSalary, avgSalary);
        personalIndexedSalary = PensionCalc.calculatePersonalIndexedSalary(avgSalary, contributionIndex);
        
        // 限制计算缴费基数在60%-300%之间
        const limitedSalary = Math.max(avgSalary * 0.6, Math.min(avgSalary * 3, currentSalary));
        personalAccountTotal = PensionCalc.calculateEmployeePAT(limitedSalary, 0.08, contributionYears);
        totalContribution = PensionCalc.calculateEmployeeTotalContribution(limitedSalary, 0.08, contributionYears);
      } else {
        // 灵活就业人员
        personalIndexedSalary = PensionCalc.calculatePersonalIndexedSalary(avgSalary, baseRate);
        personalAccountTotal = PensionCalc.calculateFreelancerPAT(avgSalary, baseRate, contributionYears);
        totalContribution = PensionCalc.calculateFreelancerTotalContribution(avgSalary, baseRate, contributionYears);
      }
      
      // 计算养老金
      const basicPension = PensionCalc.calculateBasicPension(avgSalary, personalIndexedSalary, contributionYears);
      const personalAccountPension = PensionCalc.calculatePersonalAccountPension(personalAccountTotal, payoutMonths);
      const monthlyPension = PensionCalc.calculateMonthlyPension(basicPension, personalAccountPension);
      
      // 计算收支平衡点
      const breakEvenPoint = PensionCalc.findBreakEvenPoint(totalContribution, monthlyPension);
      
      // 对于在职人员，计算税前工资与当地平均工资比例
      const salaryRatio = employmentType === 'employee' ? currentSalary / avgSalary : baseRate;
      
      chartData.push({
        avgSalary,
        breakEvenPoint,
        monthlyPension,
        totalContribution,
        salaryRatio,
        basicPension,
        personalAccountPension
      });
    }
    
    return chartData;
  }, [currentSalary, contributionYears, localAverageSalary, retirementAge, employmentType, baseRate]);

  const salaryRatioLabel = employmentType === 'employee' 
    ? '工资占平均工资比例' 
    : '选择的基准比例';

  // 使用通用tooltip格式化器
  const CustomTooltip = createTooltipFormatter({
    formatLabel: (label) => `当地平均工资: ${formatCurrency(label, false)}`,
    formatters: {
      breakEvenPoint: (value) => formatYears(value),
      monthlyPension: (value) => formatCurrency(value),
      basicPension: (value) => formatCurrency(value),
      personalAccountPension: (value) => formatCurrency(value),
      totalContribution: (value) => formatCurrency(value, false),
      salaryRatio: (value) => formatPercentage(value, 1)
    },
    nameMap: {
      breakEvenPoint: '收支平衡点',
      monthlyPension: '月养老金',
      basicPension: '基础养老金',
      personalAccountPension: '个人账户养老金',
      totalContribution: '缴费总额',
      salaryRatio: salaryRatioLabel
    }
  });
  
  const titleText = employmentType === 'employee' 
    ? `税前工资: ${formatCurrency(currentSalary, false)}`
    : `基准比例: ${formatPercentage(baseRate)}`;

  return (
    <div className="chart-container">
      <h3>当地平均工资-收支平衡点关系图</h3>
      <p className="chart-subtitle">
        {titleText}，缴费年限: {contributionYears}年
      </p>
      <p className="chart-description">
        本图表展示当地平均工资变化对养老金收支平衡点的影响。蓝色线表示收支平衡点（年），橙色线表示
        {employmentType === 'employee' ? '您的工资与当地平均工资的比例' : '您选择的基准比例'}。
        <strong>绿色垂直虚线</strong>表示当前当地平均工资水平。
        通过此图表，您可以了解当地平均工资波动如何影响您的养老金投资回报周期。
      </p>
      <ResponsiveContainer width="100%" height={400}>
        <LineChart
          data={data}
          margin={{
            top: 20,
            right: 30,
            left: 20,
            bottom: 10,
          }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis 
            dataKey="avgSalary" 
            type="number"
            label={{ value: '当地平均工资（元/月）', position: 'insideBottomRight', offset: -5 }} 
            tickFormatter={(value) => formatCurrency(value, false)}
          />
          <YAxis 
            type="number"
            label={{ value: '收支平衡点（年）', angle: -90, position: 'insideLeft' }}
            domain={['dataMin - 1', 'dataMax + 1']}
            tickFormatter={(value) => formatYears(value)}
          />
          <YAxis 
            yAxisId="right"
            orientation="right"
            domain={[0, 'auto']}
            tickFormatter={(value) => formatPercentage(value)}
            label={{ value: employmentType === 'employee' ? '工资占比' : '基准比例', angle: 90, position: 'insideRight' }}
          />
          <Tooltip content={<CustomTooltip />} />
          <Legend />
          <Line 
            type="monotone" 
            dataKey="breakEvenPoint" 
            name="收支平衡点" 
            stroke="#8884d8" 
            activeDot={{ r: 8 }} 
          />
          <Line 
            type="monotone" 
            dataKey="salaryRatio" 
            name={employmentType === 'employee' ? '工资占比' : '基准比例'} 
            stroke="#ff7300" 
            yAxisId="right"
          />
          <ReferenceLine 
            x={localAverageSalary} 
            stroke="green" 
            strokeWidth={1}
            strokeDasharray="5 5" 
            label={{ value: '当前', position: 'top', fill: 'green' }}
            ifOverflow="extendDomain"
            z={10}
          />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
};

export default BreakEvenPointByLocalSalaryChart; 